package com.cn.onetrip.activity;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.List;

import org.json.JSONException;
import org.json.JSONObject;

import com.cn.onetrip.objects.AdvertsObj;
import com.cn.onetrip.activity.R;
import com.cn.onetrip.untility.HTTPUrl;
import com.cn.onetrip.untility.ImageUtils;
import com.cn.onetrip.untility.NetworkManager;
import com.cn.onetrip.untility.ParsonJsonUtility;
import com.cn.onetrip.untility.SDCardUtils;
import com.cn.onetrip.untility.SyncImageLoader;
import com.cn.onetrip.untility.SysApplication;
import com.cn.onetrip.untility.upload;
import com.cn.onetrip.untility.SyncImageLoader.OnImageLoadListener;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.AssetManager;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.Toast;

public class IndexLoadingActivity extends Activity {

	public static boolean isOfflineData = true;
	public static boolean isCarmarHistory = false;
	public static String scenic_slug = "ynylxs";
	public String slug = "";
	private int connectCount = 0;
	private ParsonJsonUtility parsonUtility = null;
	private int AssetsList = 0;
	private int AssetsCount = 0;
	private int errorCount = 0;
	private boolean isRight = false;
	private SyncImageLoader syncImageLoader;
	private ProgressDialog progressDialog = null;
	// private LoadingView main_imageview;
	// private Thread thread;
	private Thread contentThread;
	private Thread infoThread;
	private Thread weatherThread;
	private ContentDataThread contentDataThread;
	private InfoDataThread infoDataThread;
	private WeatherDataThread weatherDatathread;
	private static boolean isReturn = false;
	private ProgressBar index_bar;
	private SysApplication sysApp;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_index_loading);
		slug = scenic_slug;
		isReturn = false;
		sysApp = new SysApplication(getApplicationContext());
		parsonUtility = new ParsonJsonUtility(this);
		index_bar = (ProgressBar) findViewById(R.id.index_bar);

		if (isCarmarHistory) {
			HTTPUrl.HistoryFloder = getApplicationContext()
					.getExternalFilesDir("OneTripMap/History/")
					.getAbsolutePath();
		}
		// main_imageview = (LoadingView) findViewById(R.id.main_imageview);
		// initLoadingImages();
		//
		// thread = new Thread() {
		// @Override
		// public void run() {
		// main_imageview.startAnim();
		// }
		// };
		// thread.start();
		copyHeadMovieFile();
		loadingData();
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
	}

	private void destroyRun() {
		// if (thread != null) {
		// main_imageview.stopAnim();
		// thread.interrupt();
		// mHandler.removeCallbacks(thread);
		// }
		if (contentThread != null) {
			mHandler.removeCallbacks(contentThread);
		}
		if (infoThread != null) {
			mHandler.removeCallbacks(infoThread);
		}
		if (weatherThread != null) {
			mHandler.removeCallbacks(weatherThread);
		}
		if (contentDataThread != null) {
			mHandler.removeCallbacks(contentDataThread);
		}
		if (infoDataThread != null) {
			mHandler.removeCallbacks(infoDataThread);
		}
		if (weatherDatathread != null) {
			mHandler.removeCallbacks(weatherDatathread);
		}
	}

	// private void initLoadingImages() {
	// int[] imageIds = new int[6];
	// imageIds[0] = R.drawable.loader_frame_1;
	// imageIds[1] = R.drawable.loader_frame_2;
	// imageIds[2] = R.drawable.loader_frame_3;
	// imageIds[3] = R.drawable.loader_frame_4;
	// imageIds[4] = R.drawable.loader_frame_5;
	// imageIds[5] = R.drawable.loader_frame_6;
	//
	// main_imageview.setImageIds(imageIds);
	// }

	private void copyHeadMovieFile() {
		String outputOcrPath = SDCardUtils
				.getFlashPath(getApplicationContext())
				+ "OneTripMap/ocr/headMovie/";
		File mWorkingPath = new File(outputOcrPath);
		File outFile = new File(mWorkingPath, "MovieHeader.mp4");

		try {
			if (!mWorkingPath.exists()) {
				if (!mWorkingPath.mkdirs()) {
					return;
				}
			}
			if (!outFile.exists()) {
				if (!outFile.createNewFile()) {
					return;
				}
			} else {
				return;
			}
			InputStream inputStream = getAssets().open("MovieHeader.mp4");

			OutputStream out = new FileOutputStream(outFile);
			byte[] buf = new byte[1024];
			int len;
			while ((len = inputStream.read(buf)) > 0) {
				out.write(buf, 0, len);
			}

			out.close();
			inputStream.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			throw new IllegalArgumentException("Move OCR tessdata Error!");
		}
	}

	private void loadingData() {
		getApplicationContext().getExternalFilesDir("ScenicGuideApp");
		try {
			HTTPUrl.JsonTextFloder = getApplicationContext()
					.getExternalFilesDir("/ScenicGuideApp/JsonText/")
					.getAbsolutePath();
			HTTPUrl.ImageCacheFloder = getApplicationContext()
					.getExternalFilesDir("ScenicGuideApp/ImageCache/")
					.getAbsolutePath();
			HTTPUrl.OfflinePackage = SDCardUtils
					.getSDPath(getApplicationContext())
					+ HTTPUrl.OfflineFloder
					+ slug;
		} catch (NullPointerException e) {
			HTTPUrl.JsonTextFloder = Environment.getExternalStorageDirectory()
					.getAbsolutePath();
			HTTPUrl.ImageCacheFloder = Environment
					.getExternalStorageDirectory().getAbsolutePath();
		}

		if (checkPixel()) {
			loadingCopyThread();
		} else {
			widthPixelsTips();
		}
	}

	private void loadingCopyThread() {
		StartCopyThread startCopyThread = new StartCopyThread();
		Thread thread = new Thread(startCopyThread);
		thread.start();
	}

	private void startLoadingData() {
		Message message = Message.obtain();
		message.what = 3;
		mHandler.sendMessage(message);

		if (sysApp != null) {
			sysApp.clearData();
		}

		if (!HTTPUrl.CheckNetworkState(getApplicationContext())
				&& isOfflineData) {
			String content = "";
			String guide_more = "";
			String OfflineJsonPath = HTTPUrl.OfflinePackage + "/" + slug
					+ ".json";
			if (new File(OfflineJsonPath).exists()) {
				content = ImageUtils.readFile(OfflineJsonPath);
			}

			String GuideMareJsonPath = HTTPUrl.OfflinePackage + "/"
					+ "guide_more.json";
			if (new File(GuideMareJsonPath).exists()) {
				guide_more = ImageUtils.readFile(GuideMareJsonPath);
			}
			if (!content.equals("")) {
				parsonUtility.parsonJsonAll(content);
				parsonUtility.parsonJsonInfo(guide_more, true);
				fillPagedata();
			} else {
				startContentLoadThread();
			}

		} else if (!HTTPUrl.CheckNetworkState(getApplicationContext())
				&& !isOfflineData) {
			Message msg = Message.obtain();
			msg.what = 1;
			mHandler.sendMessage(msg);
		} else if (HTTPUrl.CheckNetworkState(getApplicationContext())
				&& isOfflineData) {
			String OfflineJsonPath = HTTPUrl.OfflinePackage + "/" + slug
					+ ".json";
			String content = "";
			if (new File(OfflineJsonPath).exists()) {
				content = ImageUtils.readFile(OfflineJsonPath);
			}
			if (!content.equals("")) {
				parsonUtility.parsonJsonAll(content);
				startInfoLoadThread();
			} else {
				startContentLoadThread();
			}
		} else {
			startContentLoadThread();
		}
	}

	private void progressDialog() {

		Log.e("hello", "=======progressDialog");
		if (progressDialog != null) {
			progressDialog.cancel();
			progressDialog = null;
		}
		progressDialog = ProgressDialog.show(IndexLoadingActivity.this, "",
				getResources().getString(R.string.OfflineFirstLoad), true,
				false);
	}

	public class StartCopyThread implements Runnable {

		public StartCopyThread() {
		}

		@Override
		public void run() {
			SharedPreferences remindShared = getSharedPreferences("copyUnzip",
					0);
			if (!remindShared.getBoolean("isAssetsCopy", false)
					&& isOfflineData) {
				Message msg = Message.obtain();
				msg.what = 2;
				mHandler.sendMessage(msg);
				File f = new File(HTTPUrl.OfflinePackage);
				deleteFiles(f);
				if (!f.exists()) {
					if (!f.mkdirs()) {
						return;
					}
				}

				CopyAssetsPath(slug, HTTPUrl.OfflinePackage);
			} else {
				Log.e("111111111", "1111111111");
				startLoadingData();
			}
		}
	}

	public boolean CopyAssetsPath(String AssetsPath, String ObjectPath) {

		File ObjPath = new File(ObjectPath);
		if (!ObjPath.exists() || !ObjPath.isDirectory()) {
			Log.e("3DiJoy", "Object Path not found or not Dir:" + ObjectPath);
			return false;
		}
		// ObjPath = new File(ObjectPath, scenic_slug);
		// if (!ObjPath.exists()) {
		// if (!ObjPath.mkdirs()) {
		// return false;
		// }
		// }
		AssetManager am = getAssets();

		try {
			String[] FileOrDirName = am.list(AssetsPath);
			if (FileOrDirName.length <= 0) {
				Message msg = Message.obtain();
				msg.what = 1;
				copyHandler.sendMessage(msg);
				return false;
			}
			for (int i = 0; i < FileOrDirName.length; i++) {
				// if this is a DIR
				if (isAssetsDirs(AssetsPath + "/" + FileOrDirName[i])) {
					File N_DIR = new File(ObjectPath + "/" + FileOrDirName[i]);
					if (!N_DIR.exists()) {
						Log.e("3DiJoy====", String.format(
								"Will Create Dir:[%s]", ObjectPath + "/"
										+ FileOrDirName[i]));
						N_DIR.mkdir();
						AssetsCount++;
						CopyAssetsPath(AssetsPath + "/" + FileOrDirName[i],
								ObjectPath + "/" + FileOrDirName[i]);
					}
				} else // if this is file. Then copy it
				{
					Log.e("3DiJoy",
							String.format("Will Create file:[%s]", ObjectPath
									+ "/" + FileOrDirName[i]));
					if (FileOrDirName[i].endsWith(".json")) {
						AssetsCount++;
					}
					CopyAssets(AssetsPath + "/" + FileOrDirName[i], ObjectPath
							+ "/" + FileOrDirName[i]);
				}
				// Log.e("3DiJoy", String.format("File Or Dir:[%s]",
				// FileOrDirName[i]));
			}
			AssetsList = am.list(slug).length;
			if (errorCount <= 0 && AssetsList == AssetsCount) {
				if (!isRight) {
					isRight = true;
					SharedPreferences remindShared = getSharedPreferences(
							"copyUnzip", 0);
					remindShared.edit().putBoolean("isAssetsCopy", true)
							.commit();
					Message msg = Message.obtain();
					msg.what = 0;
					copyHandler.sendMessage(msg);
				}
			}
		} catch (IOException e) {
			errorCount++;
			Message msg = Message.obtain();
			msg.what = 1;
			copyHandler.sendMessage(msg);
			e.printStackTrace();
		}

		return true;
	}

	private void CopyAssets(String AssetsPath, String ObjectPath) {
		// String outputOcrPath = HTTPUrl.OfflinePackage;
		// File mWorkingPath = new File(ObjectPath);
		// File outFile = new File(mWorkingPath, "er990x7d.zip");
		File outFile = new File(ObjectPath);

		try {
			// if (!mWorkingPath.exists()) {
			// if (!mWorkingPath.mkdirs()) {
			// return;
			// }
			// }
			if (!outFile.exists()) {
				if (!outFile.createNewFile()) {
					return;
				}
			} else {
				return;
			}
			InputStream inputStream = getAssets().open(AssetsPath);

			OutputStream out = new FileOutputStream(outFile);
			byte[] buf = new byte[1024];
			int len;
			while ((len = inputStream.read(buf)) > 0) {
				out.write(buf, 0, len);
			}
			out.close();
			inputStream.close();
		} catch (IOException e) {
			e.printStackTrace();
			throw new IllegalArgumentException("Move OCR tessdata Error!");
		}
	}

	// true: Dir. false:file
	public boolean isAssetsDirs(String fileOrDirName) {
		AssetManager am = getAssets();

		try {
			am.open(fileOrDirName);
			return false;
		} catch (FileNotFoundException e) {
			return true;
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return true;
		}

		// return !(fileName.startsWith(".") || (fileName.lastIndexOf(".") !=
		// -1));
	}

	public void deleteFiles(File file) {
		if (file.exists()) {
			if (file.isFile()) {
				file.delete();
			} else if (file.isDirectory()) {
				File files[] = file.listFiles();
				for (int i = 0; i < files.length; i++) {
					deleteFiles(files[i]);
				}
			}
			file.delete();
		}
	}

	public Handler copyHandler = new Handler() {
		public void dispatchMessage(android.os.Message msg) {

			if (msg.what == 0) {
				Log.e("222222222", "22222222222");
				progressDialog.dismiss();
				startLoadingData();
			} else if (msg.what == 1) {
				Log.e("333333333", "33333333333");
				isOfflineData = false;
				progressDialog.dismiss();
				startLoadingData();
			}
		};
	};

	private void startContentLoadThread() {
		contentDataThread = new ContentDataThread(HTTPUrl.HTTP_CONTENT_URL
				+ slug + ".json?edition=2");
		contentThread = new Thread(contentDataThread);
		contentThread.start();
	}

	public class ContentDataThread implements Runnable {
		String url;

		public ContentDataThread(String url) {
			this.url = url;
		}

		@Override
		public void run() {
			try {
				new Thread().sleep(1000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			if (connectCount == 3) {
				Message msg = new Message();
				msg.what = 3;
				msg.obj = "exit";
				contentDatahandler.sendMessage(msg);
			} else {
				new upload(contentDatahandler).Http_Get_Content(url);
			}
			connectCount++;
		}
	}

	public Handler contentDatahandler = new Handler() {
		public void dispatchMessage(android.os.Message msg) {
			if (isReturn) {
				return;
			}
			if (msg.what == 0) {
				String responseJson = (String) msg.obj;
				if (responseJson != null && responseJson.length() != 0) {
					connectCount = 0;
					parsonUtility.parsonJsonAll(responseJson);

					startInfoLoadThread();
				}
			} else if (msg.what == 1) {
				startContentLoadThread();
			} else if (msg.what == 3) {
				NetworkManager.NetworkTips(IndexLoadingActivity.this);
			}
		};
	};

	private void startInfoLoadThread() {
		infoDataThread = new InfoDataThread(HTTPUrl.HTTP_INFO_URL + scenic_slug
				+ ".json?edition=2");
		infoThread = new Thread(infoDataThread);
		infoThread.start();
	}

	public class InfoDataThread implements Runnable {
		String url;

		public InfoDataThread(String url) {
			this.url = url;
		}

		@Override
		public void run() {
			// TODO Auto-generated method stub
			try {
				new Thread().sleep(1000);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			if (connectCount == 3) {
				Message msg = new Message();
				msg.what = 3;
				msg.obj = "exit";
				infoDatahandler.sendMessage(msg);
			} else {
				new upload(infoDatahandler).Http_Get_Content(url);
			}
			connectCount++;
		}
	}

	public Handler infoDatahandler = new Handler() {
		public void dispatchMessage(android.os.Message msg) {
			if (isReturn) {
				return;
			}
			if (msg.what == 0) {
				String responseJson = (String) msg.obj;
				if (responseJson != null && responseJson.length() != 0) {
					connectCount = 0;
					parsonUtility.parsonJsonInfo(responseJson, false);

					getAdsImageCache();

					startWeatherLoadThread();
				}
			} else if (msg.what == 1) {
				startInfoLoadThread();
			} else if (msg.what == 3) {
				if (isOfflineData) {
					String guide_more = "";
					String GuideMareJsonPath = HTTPUrl.OfflinePackage + "/"
							+ "guide_more.json";
					if (new File(GuideMareJsonPath).exists()) {
						guide_more = ImageUtils.readFile(GuideMareJsonPath);
					}
					if (!guide_more.equals("")) {
						parsonUtility.parsonJsonInfo(guide_more, true);
						fillPagedata();
					}
				} else {
					NetworkManager.NetworkTips(IndexLoadingActivity.this);
				}
			}
		};
	};

	private void getAdsImageCache() {
		syncImageLoader = new SyncImageLoader(this);
		List<AdvertsObj> advertsList = SysApplication.advertsList;
		for (int i = 0; i < advertsList.size(); i++) {
			final AdvertsObj advertsObj = advertsList.get(i);
			syncImageLoader.loadImage(advertsObj.advert_icon,
					new OnImageLoadListener() {

						@Override
						public void onImageLoad(Drawable drawable) {
							if (drawable != null) {
								SysApplication.adCache.put(
										advertsObj.advert_icon, drawable);
							}
						}

						@Override
						public void onImageLoad(Integer t, Drawable drawable) {
						}

						@Override
						public void onError() {
						}

						@Override
						public void onError(Integer t) {
						}
					});
		}
	}

	private void startWeatherLoadThread() {
		weatherDatathread = new WeatherDataThread(HTTPUrl.HTTP_WEATHER_URL
				+ slug + ".json?edition=2");
		weatherThread = new Thread(weatherDatathread);
		weatherThread.start();
	}

	public class WeatherDataThread implements Runnable {
		String url;

		public WeatherDataThread(String url) {
			this.url = url;
		}

		@Override
		public void run() {
			// TODO Auto-generated method stub
			try {
				new Thread().sleep(1000);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			if (connectCount == 3) {
				Message msg = new Message();
				msg.what = 3;
				msg.obj = "exit";
				weatherDatahandler.sendMessage(msg);
			} else {
				new upload(weatherDatahandler).Http_Get_Content(url);
			}
			connectCount++;
		}
	}

	public Handler weatherDatahandler = new Handler() {
		public void dispatchMessage(android.os.Message msg) {
			if (isReturn) {
				return;
			}
			if (msg.what == 0) {
				String responseJson = (String) msg.obj;
				if (responseJson != null && responseJson.length() != 0) {
					parsonUtility.parsonJsonWeather(responseJson);
					fillPagedata();
				}
			} else if (msg.what == 1) {
				fillPagedata();
				// startWeatherLoadThread();
			} else if (msg.what == 3) {
				fillPagedata();
				// NetworkManager.NetworkTips(IndexLoadingActivity.this);
			}
		};
	};

	public void saveHistory() {
		if (!isCarmarHistory) {
			return;
		}
		isCarmarHistory = false;
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		String date = sdf.format(new java.util.Date());
		SimpleDateFormat historydate = new SimpleDateFormat("yyyyMMddHHmmss");
		String historyName = historydate.format(new java.util.Date());
		historyName = historyName.replace(" ", "");
		JSONObject json = new JSONObject();
		try {
			json.put("name", SysApplication.contentObj.title);
			json.put("slug", slug);
			json.put("scan_time", date);
			json.put("file_size", "");
			json.put("type", 0x17);
			json.put("pic_url", "");
			new ImageUtils().saveJsonFile(json.toString(),
					HTTPUrl.HistoryFloder, historyName);
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	private void fillPagedata() {
		saveHistory();
		Message msg = Message.obtain();
		msg.what = 0;
		mHandler.sendMessage(msg);
	}

	public Handler mHandler = new Handler() {
		public void dispatchMessage(android.os.Message msg) {

			if (msg.what == 0) {
				index_bar.setVisibility(View.GONE);
				destroyRun();
				Intent intent = null;
				SharedPreferences remindShared = getSharedPreferences(
						"GuiderActivity", 0);
				boolean isFirstGuider = remindShared.getBoolean("isFirstEnter",
						false);
				if (TripActivity.One_Trip) {
					intent = new Intent(getApplicationContext(),
							TripActivity.class);
				} else {
					intent = new Intent(getApplicationContext(),
							isFirstGuider ? TripActivity.class
									: ScenicGuiderActivity.class);
				}

				startActivity(intent);
				finish();
				overridePendingTransition(R.anim.push_right_translate,
						R.anim.pull_left_translate);
			} else if (msg.what == 1) {
				index_bar.setVisibility(View.GONE);
				destroyRun();
				NetworkManager.NetworkTips(IndexLoadingActivity.this);
			} else if (msg.what == 2) {
				progressDialog();
			} else if (msg.what == 3) {
				index_bar.setVisibility(View.VISIBLE);
			}
		};
	};

	private boolean checkPixel() {
		DisplayMetrics displayMetrics = new DisplayMetrics();
		getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);

		if (displayMetrics.widthPixels < getResources().getInteger(
				R.integer.min_displayMetrics_widthpixel)) {
			return false;
		} else {
			return true;
		}
	}

	public void widthPixelsTips() {
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setIcon(android.R.drawable.ic_dialog_alert);
		builder.setTitle(R.string.width_pixel_warring);
		builder.setMessage(R.string.width_pixel_warring_info);
		builder.setNegativeButton(R.string.width_pixel_configm,
				new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						Log.e("444444444", "4444444444");
						startLoadingData();
					}
				});
		builder.setPositiveButton(R.string.quit,
				new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						android.os.Process.killProcess(android.os.Process
								.myPid());
						finish();
					}
				});
		builder.create();
		builder.show();
	}

	private void returnClick() {
		isReturn = true;
		destroyRun();
		if (sysApp != null) {
			sysApp.clearData();
		}
		System.gc();
		finish();
		overridePendingTransition(R.anim.push_left_translate,
				R.anim.pull_right_translate);
		if (isOfflineData) {
			android.os.Process.killProcess(android.os.Process.myPid());
			java.lang.System.exit(0);
		}
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
			returnClick();
		}
		return super.onKeyDown(keyCode, event);
	}
}
